package main;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

public class Formula {

	private static ArrayList<String> formulas=new ArrayList<String>(); //provisorio
	
	public boolean addFormula(String formula){
		return formulas.add(formula);
	}
	public void deleteFormula(int index){
		formulas.remove(index);
	}
	public static void setFormulas(ArrayList<String> formulas) {
		Formula.formulas = formulas;
	}
	public static ArrayList<String> getFormulas() {
		return formulas;
	}
	
	public static int getSize(){
		return formulas.size();
	}
	public byte[] toByte(){
		
		ByteArrayOutputStream bout=new ByteArrayOutputStream();
		DataOutputStream dataOut=new DataOutputStream(bout);
		
		for(String i: formulas)
			try {
				dataOut.writeUTF(i);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		byte[] bytes=bout.toByteArray();
		return bytes;
	}
	
	public void SaveinFile(){
		try {
			FileOutputStream fos=new FileOutputStream("CalculadoraData");
			fos.write(toByte(), 0, getSize());
			fos.flush();
			fos.close();
			
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			System.err.println("Error - "+e1);
		}
	}
	
	public void ReadFile(){ /*Verificar*/
		
		ArrayList<String> x=new ArrayList<String>();;
		File input=new File("CalculadoraData");
		if(input!=null){
			byte[] data=new byte[(int) input.length()];
			FileInputStream fis;
			try {
				fis = new FileInputStream(input);
				x.addAll(fis.read(data, 0, data.length), x);
				fis.close();
				
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			setFormulas(x);
		}
		
		
	}
}
